package datasource

import (
	"fmt"
	"log"
	"time"
	"zzxq/common/setting"
	"zzxq/models"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"gorm.io/plugin/dbresolver"
)

var getDb *gorm.DB

//Connect 初始化数据库配置
func Connect() error {

	conf := setting.Config.Database

	db0_dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&loc=Local", conf[0].User, conf[0].Password, conf[0].Host, conf[0].DbName)
	db1_dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&loc=Local", conf[1].User, conf[1].Password, conf[1].Host, conf[1].DbName)

	db, err := gorm.Open(mysql.Open(db0_dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
		SkipDefaultTransaction: true,
	})
	
	if err != nil {
		log.Println("Connect Mysql Fail", err)
		return err
	}

	db.Use(
		dbresolver.Register(dbresolver.Config{
			Sources: []gorm.Dialector{mysql.Open(db0_dsn)},
		}).
		Register(dbresolver.Config{
			Sources: []gorm.Dialector{mysql.Open(db1_dsn)},
		}, &models.Remind{}).
		SetConnMaxIdleTime(time.Hour).
		SetConnMaxLifetime(24 * time.Hour).
		SetMaxIdleConns(100).
		SetMaxOpenConns(200)) //绑定对应的表结构到数据库，未绑定则默认走1库

	log.Println("Connect Mysql Success")

	getDb = db

	return nil
}

func GetDb() *gorm.DB {
	return getDb
}
